# -*- coding: utf-8 -*-
"""
For Land Classification Statictics
as the support for classification mapping among ESA, Gong and Yu.

Created on Thu Jun 18 10:47:28 2020

@author: Farman
"""

import fast_histogram
import numpy


def get_histogram(array):
    a_min, a_max = array.min(), array.max()
    histo = fast_histogram.histogram1d(array, a_max - a_min + 1, 
                              (a_min, a_max + 1))
    
    histo = numpy.array(histo, dtype='int')
    
    hist = {}
    
    for n in range(a_min, a_max + 1):
        if histo[n - a_min] > 0:
            hist.update({n:histo[n - a_min]})

    return hist



def show_histogram(histo):
    ks = sorted(histo.keys())
    
    print('\n  value |\tcount')
    print('-' * 20)
    for k in ks:
        print('%7d | %8d'%(k, histo.get(k)))
        
    return


def get_unique_value_list(histo):
    uvs = sorted(histo.keys())
    return uvs



def get_most_significant_value(histo):    
    biggest = None
    
    for k in histo.keys():
        if biggest == None:
            biggest = k
        else:
            if histo.get(k) > histo.get(biggest):
                biggest = k
    
    return biggest


#'''
#=======================================================
import MyTimer
import GeotiffMan

tiff_china = r'clscmp_test_data/N37E119_2010_landcover.tif'
tiff_usa   = r'clscmp_test_data/N37E119-ESACCI-LC-L4-LCCS-Map-300m-P1Y-2010-v2.0.7.tif'
tiff_usa   = r'D:\CUIT-Farman\Data\GlobalLandClassificationDataFromUSA\ESACCI\ESACCI-LC-L4-LCCS-Map-300m-P1Y-1992-v2.0.7.tif'
geo_china = GeotiffMan.GeoTiffMan(tiff_china)
geo_usa   = GeotiffMan.GeoTiffMan(tiff_usa)

#geo_china.show_info()
#geo_usa.show_info()

data_china = geo_china.read_band(1)
data_usa   = geo_usa.read_band(1)

histo_china = get_histogram(data_china)
histo_usa   = get_histogram(data_usa)

print(get_unique_value_list(histo_china))
print(get_unique_value_list(histo_usa))

print(get_most_significant_value(histo_china))
print(get_most_significant_value(histo_usa))

show_histogram(histo_china)
show_histogram(histo_usa)
#========================================================'''